﻿using CKS2320.Common;
using CKS2320.Common.Model;
using CKS2320.Common.Transfer;
using CKS2320.Domain.DBEntity;
using CKS2320.Repository.Interface;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Abstractions;
using Newtonsoft.Json;
using NPOI.SS.Formula.Functions;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;

namespace CKS2320.Repository
{
    public class CksLargeTotalRepository : ICksLargeTotalRepository
    {
        private DBContext _dBContext;
        public CksLargeTotalRepository(DBContext dBContext)
        {
            _dBContext = dBContext;
        }
        public int GetAllCount(string Starttime, string Endtime, bool f)
        {
            int total = 0;
            if (f)
            {
                total += _dBContext.Shapes.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime));
                // total += _dBContext.Voltagewithstands.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime));
                // total += _dBContext.Thicknessdetections.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime));
            }
            else
            {
                // total += _dBContext.Shapes.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == true);
                // total += _dBContext.Voltagewithstands.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == true);
                total += _dBContext.Thicknessdetections.Count(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == true);
            }
            return total;
        }

        public List<DefectiveDto> GetdefectiveList(string Starttime, string Endtime)
        {
            string sql = string.Format(@"Select COUNT(1) as Num,[PartCode] from [shape] where Result=0 and CreatedTime>=CONVERT(nvarchar(100),'{0}',20) and CreatedTime<=CONVERT(nvarchar(100),'{1}',20)  group by [PartCode] union all   Select COUNT(1) as Num,[PartCode] from [voltagewithstand] where Result = 0 and CreatedTime>=CONVERT(nvarchar(100),'{0}',20) and CreatedTime<=CONVERT(nvarchar(100),'{1}',20)  group by [PartCode] union all  Select COUNT(1) as Num,[PartCode] from [thicknessdetection]  where  CreatedTime>=CONVERT(nvarchar(100),'{0}',20) and CreatedTime<=CONVERT(nvarchar(100),'{1}',20) and  Result=0  group by [PartCode]", Starttime, Endtime);
            return _dBContext.Database.SqlQuery<DefectiveDto>(sql).ToList();
        }
        public List<AllStationCodeDto> GetTotalCount1(string Starttime, string Endtime, int r)
        {
            List<AllStationCodeDto> listAll = new();
            if (r == 1)
            {
                listAll.AddRange(_dBContext.Shapes
                    .Where(n => n.CreatedTime >= DateTime.Parse(Starttime) && n.CreatedTime <= DateTime.Parse(Endtime) && n.Result == false)
                    .Select(p => new AllStationCodeDto() { CreatedTime = p.CreatedTime, StationCode = p.StationCode }).ToList());
            }
            if (r == 2)
            {
                listAll.AddRange(_dBContext.Voltagewithstands
                    .Where(n => n.CreatedTime >= DateTime.Parse(Starttime) && n.CreatedTime <= DateTime.Parse(Endtime) && n.Result == false)
                    .Select(p => new AllStationCodeDto() { CreatedTime = p.CreatedTime, StationCode = p.StationCode }).ToList());
            }
            if (r == 3)
            {
                listAll.AddRange(_dBContext.Thicknessdetections
                    .Where(p => p.CreatedTime >= DateTime.Parse(Starttime) && p.CreatedTime <= DateTime.Parse(Endtime) && p.Result == false)
                    .Select(p => new AllStationCodeDto() { CreatedTime = p.CreatedTime, StationCode = p.StationCode }).ToList());
            }
            return listAll;
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public DataQueryResponse QueryListCount()
        {
            DataQueryResponse result = new();
            var shapesList = _dBContext.Shapes.AsNoTracking().ToList();
            var voltageList = _dBContext.Voltagewithstands.AsNoTracking().ToList();
            var thicknessdetectionList = _dBContext.Thicknessdetections.AsNoTracking().ToList();

            result.totalOK += shapesList.Where(p => p.Result == true).Count();
            result.totalOK += voltageList.Where(p => p.VoltageWithstandResult == true).Count();
            result.totalOK += voltageList.Where(p => p.CameraDetectionResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult1 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult2 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult3 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult4 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult5 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult6 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.BackThicknessResult7 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult1 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult2 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult3 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult4 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult5 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult6 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FrontThicknessResult7 == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.Crfront1WaveDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.Crfront64WaveDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.CrlargeEndDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.CrsmallEndDistanceResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.FacadeCurvatureResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.SmallEndDirectionInspectionResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p.TotalLengthResult == true).Count();
            result.totalOK += thicknessdetectionList.Where(p => p._3dscannerResult == true).Count();

            result.totalNG += shapesList.Where(p => p.Result == false).Count();
            result.totalNG += voltageList.Where(p => p.VoltageWithstandResult == false).Count();
            result.totalNG += voltageList.Where(p => p.CameraDetectionResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult1 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult2 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult3 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult4 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult5 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult6 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.BackThicknessResult7 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult1 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult2 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult3 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult4 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult5 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult6 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FrontThicknessResult7 == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.Crfront1WaveDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.Crfront64WaveDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.CrlargeEndDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.CrsmallEndDistanceResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.FacadeCurvatureResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.SmallEndDirectionInspectionResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p.TotalLengthResult == false).Count();
            result.totalNG += thicknessdetectionList.Where(p => p._3dscannerResult == false).Count();
            return result;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public List<Detectiondetail> QueryList(TotalReq req, PLCRunTypeEnum pLCRunTypeEnum)
        {
            string sqlType = req.Type == 0 ? " a.rn=1" : " 1=1";
            string sql = string.Format($@"select  a.[Id],a.[ParentId],a.[PartCode],a.[PLCIP],a.[DetectedData],a.[DetectedType],a.[DetectedTypeDisplay],a.[DetectedIndex],a.[DetectedStatus],a.[DetectedTime],a.[Description],a.[CreatedTime],a.[ModifiedTime] from (SELECT  [Id] ,[ParentId] ,[PartCode] ,[PLCIP],[DetectedData],[DetectedType],[DetectedTypeDisplay],[DetectedIndex],[DetectedStatus],[DetectedTime],[Description],[CreatedTime],[ModifiedTime],ROW_NUMBER() OVER (PARTITION BY DetectedIndex ORDER BY CreatedTime desc ) AS rn FROM  detectiondetail) a 
                            left join (select distinct partcode from [dbo].[thicknessdetection]) b on a.partcode = b.partcode
                            where {sqlType}  and a.description='{pLCRunTypeEnum.ToString()}'  order by createdTime desc ");
            if (req.Type == 0 && req.page != null && req.size != null)
            {
                var query = _dBContext.Database.SqlQuery<Detectiondetail>(sql).Skip((req.page.Value - 1) * req.size.Value).Take(req.size.Value).ToList();
                return query;
            }
            var query2 = _dBContext.Database.SqlQuery<Detectiondetail>(sql).ToList();
            return query2;
        }
        /// <summary>
        /// 导出查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public List<ExportQueryListModel> ExportQueryList(PLCRunTypeEnum pLCRunTypeEnum)
        {
            string sql = string.Format($@"select a.PartCode,a.PLCIP,
case when a.PLCIP='192.168.10.100' then 'OP10'
when a.PLCIP='192.168.10.120' then 'OP20'
when a.PLCIP='192.168.10.150' then 'OP30' end StationCode,a.DetectedData,a.DetectedType,a.Description,a.CreatedTime from 
                            (SELECT *,ROW_NUMBER() OVER (PARTITION BY DetectedIndex ORDER BY CreatedTime desc ) AS rn FROM  detectiondetail) a 
                            left join (select distinct partcode from [dbo].[thicknessdetection]) b on a.partcode = b.partcode
                            where a.description='{pLCRunTypeEnum.ToString()}'  order by createdTime desc ");
            var query = _dBContext.Database.SqlQuery<ExportQueryListModel>(sql).ToList();
            return query;
        }
        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        public OPResult QueryByPartCodeList(string partCode)
        {
            OPResult result = new()
            {
                partCode = partCode
            };
            var shapeList = _dBContext.Shapes.Where(p => p.PartCode == partCode).ToList();
            if (shapeList != null && shapeList.Any())
            {
                foreach (var item in shapeList)
                {
                    result.op10s.Add(new OP10Result() { parentId = item.Id, result = item.Result });
                }
            }
            var voltageList = _dBContext.Voltagewithstands.Where(p => p.PartCode == partCode).ToList();
            if (voltageList != null && voltageList.Any())
            {
                foreach (var item in voltageList)
                {
                    result.op20s.Add(new OP20Result()
                    {
                        parentId = item.Id,
                        result = item.Result,
                        CameraDetectionResult = item.CameraDetectionResult,
                        VoltageWithstandResult = item.VoltageWithstandResult
                    });
                }
            }
            var thicknessList = _dBContext.Thicknessdetections.Where(p => p.PartCode == partCode).ToList();
            if (thicknessList != null && thicknessList.Any())
            {
                foreach (var item in thicknessList)
                {
                    result.op30s.Add(new OP30Result()
                    {
                        parentId = item.Id,
                        result = item.Result,
                        BackThicknessResult1 = item.BackThicknessResult1,
                        BackThicknessResult2 = item.BackThicknessResult2,
                        BackThicknessResult3 = item.BackThicknessResult3,
                        BackThicknessResult4 = item.BackThicknessResult4,
                        BackThicknessResult5 = item.BackThicknessResult5,
                        BackThicknessResult6 = item.BackThicknessResult6,
                        BackThicknessResult7 = item.BackThicknessResult7,
                        Crfront1WaveDistanceResult = item.Crfront1WaveDistanceResult,
                        Crfront64WaveDistanceResult = item.Crfront64WaveDistanceResult,
                        CrlargeEndDistanceResult = item.CrlargeEndDistanceResult,
                        CrsmallEndDistanceResult = item.CrsmallEndDistanceResult,
                        FacadeCurvatureResult = item.FacadeCurvatureResult,
                        FrontThicknessResult1 = item.FrontThicknessResult1,
                        FrontThicknessResult2 = item.FrontThicknessResult2,
                        FrontThicknessResult3 = item.FrontThicknessResult3,
                        FrontThicknessResult4 = item.FrontThicknessResult4,
                        FrontThicknessResult5 = item.FrontThicknessResult5,
                        FrontThicknessResult6 = item.FrontThicknessResult6,
                        FrontThicknessResult7 = item.FrontThicknessResult7,
                        SmallEndDirectionInspectionResult = item.SmallEndDirectionInspectionResult,
                        TotalLengthResult = item.TotalLengthResult,
                        _3dscannerResult1 = item._3dscannerResult
                    });
                }
            }
            return result;
        }
        public List<DataQueryListModel> QueryListDetail(List<Detectiondetail> detailList, IEnumerable<Indicatortolerancezone> indicatorToleranceZonesList, PLCRunTypeEnum PLCRunType)
        {
            List<DataQueryListModel> result = new();
            #region 查询所有检测项
            List<Detectiondetail> All = new();
            var parentList = detailList.Select(p => p.ParentId).Distinct().ToList();
            foreach (var item in parentList)
            {
                All.AddRange(_dBContext.Detectiondetails.Where(p => p.ParentId == item).AsNoTracking().ToList());
            }
            #endregion

            List<OPResult> opResult = new();
            var partCodeList = detailList.Select(p => p.PartCode).Distinct().ToList();
            foreach (var item in partCodeList)
            {
                opResult.Add(QueryByPartCodeList(item));
            }
            float? PartLength = All.FirstOrDefault(p => p.DetectedIndex == 10)?.DetectedData;
            foreach (var detail in detailList)
            {
                DataQueryListModel queryModel = new()
                {
                    RunType = PLCRunType.ToString(),
                    DetectedData = detail.DetectedData,
                    PartCode = detail.PartCode ?? "",
                    PartLength = PartLength.ToString() ?? "",
                    DetectedType = detail.DetectedTypeDisplay ?? "",
                    DetectedTime = detail.DetectedTime ?? ""
                };
                bool indicator = true;
                var itemDetail = All.Where(p => p.ParentId == detail.ParentId && p.DetectedIndex == detail.DetectedIndex).ToList();
                foreach (var item in itemDetail)
                {
                    var opInfo = opResult.FirstOrDefault(p => p.partCode == item.PartCode);
                    if (opInfo != null)
                    {
                        bool? op10result = opInfo?.op10s.Where(p => p.parentId == item.ParentId).Select(p => p.result).FirstOrDefault();
                        bool? op20result = opInfo?.op20s.Where(p => p.parentId == item.ParentId).Select(p => p.result).FirstOrDefault();
                        bool? op30result = opInfo?.op30s.Where(p => p.parentId == item.ParentId).Select(p => p.result).FirstOrDefault();
                        if (op10result == true || op20result == true || op30result == true)
                        {
                            indicator = true;
                        }
                        else
                        {
                            indicator = QueryListDetailInfo(item, indicatorToleranceZonesList);
                        }
                    }
                    else
                    {
                        indicator = QueryListDetailInfo(item, indicatorToleranceZonesList);
                    }
                }
                queryModel.Indicator = indicator;
                queryModel.ToleranceZone = indicator;
                queryModel.DetectedResult = indicator;
                result.Add(queryModel);
            }
            return result;
        }
        public bool QueryListDetailInfo(Detectiondetail item, IEnumerable<Indicatortolerancezone> indicatorToleranceZonesList)
        {
            bool indicator = true;
            if (item.DetectedData == 0 || item.DetectedData == 1)
            {
                if (item.DetectedData == 0)
                    indicator = false;
            }
            else
            {
                Indicatortolerancezone indicatortolerancezone = indicatorToleranceZonesList.FirstOrDefault(p => p.Content == item.DetectedType);
                if (indicatortolerancezone != null)
                {
                    if (indicatortolerancezone.ContentType == "0") //正负范围
                    {
                        if ((indicatortolerancezone.Indicator + indicatortolerancezone.ToleranceZone) < item.DetectedData
                            || (indicatortolerancezone.Indicator - indicatortolerancezone.ToleranceZone) > item.DetectedData)
                        {
                            indicator = false;
                        }
                    }
                    else if (indicatortolerancezone.ContentType == "1") //最大值
                    {
                        if (indicatortolerancezone.ToleranceZone < item.DetectedData)
                        {
                            indicator = false;
                        }
                    }
                    else if (indicatortolerancezone.ContentType == "2") //最小值
                    {
                        if (indicatortolerancezone.ToleranceZone > item.DetectedData)
                        {
                            indicator = false;
                        }
                    }
                }
            }
            return indicator;
        }
        /// <summary>
        /// 历史数据趋势
        /// </summary>
        /// <param name="req"></param>
        public IEnumerable<Detectiondetail> HistoryDataTrends(string data, int detectedIndex)
        {
            DateTime startDate = Convert.ToDateTime(data + " 00:00:00");
            DateTime endDate = Convert.ToDateTime(data + " 23:59:59");
            return _dBContext.Detectiondetails.Where(p => p.DetectedIndex == detectedIndex && p.CreatedTime >= startDate && p.CreatedTime <= endDate).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
        }
        /// <summary>
        /// 指标 公差带
        /// </summary>
        /// <returns></returns>
        public IEnumerable<Indicatortolerancezone> GetIndicatorToleranceZones()
        {
            //var result = _dBContext.IndicatorToleranceZones.AsNoTracking().OrderBy(p => p.Content).ToList();
            //List<IndicatorToleranceZoneModel> json = new();
            //foreach (var item in result)
            //{
            //    json.Add(new IndicatorToleranceZoneModel()
            //    {
            //        Plcip = item.Plcip,
            //        Indicator = item.Indicator,
            //        ToleranceZone = item.ToleranceZone,
            //        Content = item.Content,
            //        ContentType = item.ContentType
            //    });
            //}
            //string values = JsonConvert.SerializeObject(json);

            //return _dBContext.IndicatorToleranceZones.AsNoTracking().ToList();
            string text = File.ReadAllText("Indicatortolerancezone.json");
            return JsonConvert.DeserializeObject<List<Indicatortolerancezone>>(text);
        }
        ///// <summary>
        ///// 导出
        ///// </summary>
        ///// <param name="req"></param>
        ///// <returns></returns>
        //public List<ThicknessDetectionModel> ExportQueryList(TotalReq req)
        //{
        //    //var query = _dbCotext.Detectiondetails.OrderByDescending(p=>p.CreatedTime).GroupBy(p=>p.DetectedType)
        //    //                        .Skip((req.page.Value - 1) * req.size.Value).Take(req.size.Value).ToList();


        //    var filters = new List<Func<Thicknessdetection, bool>>();
        //    if (!string.IsNullOrEmpty(req.StartTime))
        //    {
        //        filters.Add(p => p.CreatedTime >= Convert.ToDateTime(req.StartTime));
        //    }
        //    if (!string.IsNullOrEmpty(req.EndTime))
        //    {
        //        filters.Add(p => p.CreatedTime <= Convert.ToDateTime(req.EndTime));
        //    }
        //    if (!string.IsNullOrEmpty(req.Status))
        //    {
        //        filters.Add(p => p.Result == (req.Status.ToLower() == "ok"));
        //    }
        //    List<Thicknessdetection> thicknessdetections = new();
        //    var query = _dBContext.Thicknessdetections.Where(p => filters.All(filter => filter(p))).OrderByDescending(p => p.CreatedTime);
        //    if (req.page != null && req.size != null)
        //    {
        //        thicknessdetections = query.Skip((req.page.Value - 1) * req.size.Value).Take(req.size.Value).ToList();
        //    }
        //    else
        //    {
        //        thicknessdetections = query.ToList();
        //    }
        //    if (thicknessdetections != null && thicknessdetections.Any())
        //    {
        //        var qs = from a in thicknessdetections
        //                 join b in _dbCotext.Detectiondetails on a.Id equals b.ParentId
        //                 select new ThicknessDetectionModel
        //                 {
        //                     BackThicknessResult1 = a.BackThicknessResult1,
        //                     BackThicknessResult2 = a.BackThicknessResult2,
        //                     BackThicknessResult3 = a.BackThicknessResult3,
        //                     BackThicknessResult4 = a.BackThicknessResult4,
        //                     BackThicknessResult5 = a.BackThicknessResult5,
        //                     BackThicknessResult6 = a.BackThicknessResult6,
        //                     BackThicknessResult7 = a.BackThicknessResult7,
        //                     FrontThicknessResult1 = a.FrontThicknessResult1,
        //                     FrontThicknessResult2 = a.FrontThicknessResult2,
        //                     FrontThicknessResult3 = a.FrontThicknessResult3,
        //                     FrontThicknessResult4 = a.FrontThicknessResult4,
        //                     FrontThicknessResult5 = a.FrontThicknessResult5,
        //                     FrontThicknessResult6 = a.FrontThicknessResult6,
        //                     FrontThicknessResult7 = a.FrontThicknessResult7,
        //                     Crfront1WaveDistanceResult = a.Crfront1WaveDistanceResult,
        //                     Crfront64WaveDistanceResult = a.Crfront64WaveDistanceResult,
        //                     CrlargeEndDistanceResult = a.CrlargeEndDistanceResult,
        //                     CrsmallEndDistanceResult = a.CrsmallEndDistanceResult,
        //                     EndUpLoad = a.EndUpLoad,
        //                     FacadeCurvatureResult = a.FacadeCurvatureResult,
        //                     SmallEndDirectionInspectionResult = a.SmallEndDirectionInspectionResult,
        //                     StationCode = a.StationCode,
        //                     TotalLengthResult = a.TotalLengthResult,
        //                     _3dscannerEnd = a._3dscannerEnd,
        //                     _3dscannerResult1 = a._3dscannerResult,
        //                     _3dscannerStart = a._3dscannerStart,
        //                     Heart1 = a.Heart1,
        //                     Heart2 = a.Heart2,
        //                     StartUpLoad = a.StartUpLoad,
        //                     PartCode = a.PartCode,
        //                     Result = a.Result,
        //                     RunType = a.RunType,
        //                     detaillist = new List<DetectionDetail>()
        //                     {
        //                         new DetectionDetail()
        //                         {
        //                             Id = b.Id, ParentId = b.ParentId,
        //                             Description = b.Description,
        //                             DetectedData = b.DetectedData,
        //                             DetectedType = b.DetectedType
        //                         }}
        //                 };

        //        return qs.ToList();
        //    }
        //    return new List<ThicknessDetectionModel>();
        //}

        public Hashtable GetToDoMesData()
        {

            List<Shape> splist = _dBContext.Shapes.Where(p => p.Pushed == false).ToList();
            List<Detectiondetail> Shapedetaillist = new List<Detectiondetail>();
            foreach (Shape shape in splist)
            {
                shape.Pushed = true;
                Shapedetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == shape.Id).ToList();
                shape.detaillist = Shapedetaillist;
            }
            List<Voltagewithstand> vllist = _dBContext.Voltagewithstands.Where(p => p.Pushed == false).ToList();
            List<Detectiondetail> vldetaillist = new List<Detectiondetail>();
            foreach (Voltagewithstand vl in vllist)
            {
                vl.Pushed = true;
                vldetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == vl.Id).ToList();
                vl.detaillist = Shapedetaillist;
            }
            List<Thicknessdetection> tklist = _dBContext.Thicknessdetections.Where(p => p.Pushed == false).ToList();
            List<Detectiondetail> tkdetaillist = new List<Detectiondetail>();
            foreach (Thicknessdetection tk in tklist)
            {
                tk.Pushed = true;
                tkdetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == tk.Id).ToList();
                tk.detaillist = Shapedetaillist;
            }
            Hashtable hashtable = new Hashtable();
            hashtable.Add("OP10", splist);
            hashtable.Add("OP20", vllist);
            hashtable.Add("OP30", tklist);

            return hashtable;
        }

        public async Task<DataQueryResponseNew> QueryListCountNew(TotalReq totalReq)
        {
            DataQueryResponseNew model = new();

            List<DataQuery> list = new();
            int OK = 0;
            int NG = 0;
            int camberNG = 0;
            int ThicknessNG = 0;
            int BOWNG = 0;
            int OtherNG = 0;
            List<Op10coredata> OP10List = new List<Op10coredata>();
            List<Op20coredata> OP20List = new List<Op20coredata>();
            List<Op30coredata> OP30List = new List<Op30coredata>();
            List<PerformanceRecord> OEElist = new List<PerformanceRecord>();
            if (!string.IsNullOrEmpty(totalReq.StartTime) && !string.IsNullOrEmpty(totalReq.EndTime))
            {

                DateTime start = DateTime.Parse(totalReq.StartTime);
                DateTime end = DateTime.Parse(totalReq.EndTime); ;
                OP10List = _dBContext.Op10coreDatas.Where(p => p.TestTime >= start && p.TestTime <= end).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
                OP20List = _dBContext.Op20coreDatas.Where(p => p.TestTime >= start && p.TestTime <= end).AsNoTracking().ToList();
                OP30List = _dBContext.Op30coreDatas.Where(p => p.TestTime >= start && p.TestTime <= end).AsNoTracking().ToList();
                OEElist = _dBContext.PerformanceRecords.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
            }
            else if (!string.IsNullOrEmpty(totalReq.StartTime))
            {
                DateTime start = DateTime.Parse(totalReq.StartTime);
                OP10List = _dBContext.Op10coreDatas.Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
                OP20List = _dBContext.Op20coreDatas.Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
                OP30List = _dBContext.Op30coreDatas.Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
                OEElist = _dBContext.PerformanceRecords.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
            }
            else
            {
                DateTime start = DateTime.Now.AddDays(-3);
                //默认只取3天的数据
                OP10List = _dBContext.Op10coreDatas.Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
                OP20List = _dBContext.Op20coreDatas.Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
                OP30List = _dBContext.Op30coreDatas.Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
                OEElist = _dBContext.PerformanceRecords.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).AsNoTracking().ToList();
            }
            model = await asyncGetCount();
            if (totalReq.size > 0)
            {
                OP10List = OP10List.Skip((totalReq.page.Value - 1) * totalReq.size.Value).Take(totalReq.size.Value).ToList();
            }
            foreach (var item in OP10List)
            {

                DataQuery dataQuery = new DataQuery();
                dataQuery.PartCode = item.SerialNumber;
                dataQuery.ShapeID = item.Id.ToString();
                dataQuery.RunType = item.Passageway;
                dataQuery.BOW = item?.HorizontalCamber.ToString();
                //OP20
                Op20coredata? Op20model = OP20List.Where(p => p.SerialNumber == item.SerialNumber && (item.Judge == "OK" || p.TestTime < item.TestTime.Value.AddMinutes(20)) &&
                   p.TestTime > item.TestTime).OrderByDescending(p => p.TestTime).LastOrDefault();
                if (Op20model == null)
                {
                    list.Add(dataQuery);
                    continue;
                }
                dataQuery.VoltagewithstandID = Op20model.Id.ToString();
                dataQuery.POT = Op20model?.CurrentDc.ToString();
                dataQuery.TotalLength = Op20model?.TotalLength.ToString();
                //OP30
                Op30coredata? OP30nodel = OP30List.Where(p => p.SerialNumber == item.SerialNumber && ((Op20model.ResultDc == "OK" && Op20model.ResultAc == "OK") || p.TestTime < Op20model.TestTime.Value.AddMinutes(20)) &&
                     p.TestTime > Op20model.TestTime).OrderByDescending(p => p.TestTime).LastOrDefault();
                if (OP30nodel == null)
                {
                    list.Add(dataQuery);
                    continue;
                }
                dataQuery.ThicknessdetectionID = OP30nodel.Id.ToString();
                dataQuery.Camber = OP30nodel.FacadeCamber?.ToString();
                dataQuery.sc01 = OP30nodel.sc01?.ToString();
                dataQuery.sc02 = OP30nodel.sc02?.ToString();
                dataQuery.sc03 = OP30nodel.sc03?.ToString();
                dataQuery.sc04 = OP30nodel.sc04?.ToString();

                dataQuery.fctmax = OP30nodel.MaxThickness?.ToString();
                dataQuery.fctmin = OP30nodel.MiniThickness?.ToString();
                dataQuery.bctmax = OP30nodel.NonPositiveMaxThickness?.ToString();
                dataQuery.bctmin = OP30nodel.NonPositiveMiniThickness?.ToString();
                if (OP30nodel.MaxThicknessJudge == "OK" && OP30nodel.MiniThicknessJudge == "OK")
                {
                    dataQuery.Thickness = "OK";
                }
                else
                {
                    dataQuery.Thickness = "NG";
                }
                if (OP30nodel.FinalJudge == "OK")
                {
                    dataQuery.Result = "OK";
                }
                else
                {
                    dataQuery.Result = "NG";
                }
                list.Add(dataQuery);
            }
            model.listA = list.Where(p => p.RunType == "A").ToList();
            model.listB = list.Where(p => p.RunType == "B").ToList();
            if (OEElist.Count > 0)
            {
                model.totalRunTime = OEElist[0].TotalRunTime;
                model.faultTime = OEElist[0].FaultTime;
                model.OEE = OEElist[0].OEE;
                model.holdTime = OEElist[0].ProductYield;
                model.stopTime = OEElist[0].StopTime;
            }
            else
            {
                model.totalRunTime = 0;
                model.faultTime = 0;
                model.holdTime = 0;
                model.stopTime = 0;
                model.OEE = 0;

            }
            return model;
        }

        public async Task<DataQueryResponseNew> asyncGetCount()
        {
            DataQueryResponseNew model = new();
            List<Op10coredata> OP10List = _dBContext.Op10coreDatas.ToList();
            List<Op30coredata> OP30List = _dBContext.Op30coreDatas.Where(p => p.FinalJudge == "OK").ToList();
            int OK = 0;
            int NG = 0;
            model.Detected = OP10List.Count;
            model.OK = OP30List.Count;
            model.NG = OP10List.Count - OP30List.Count;
            //foreach (Op10coredata op10model in OP10List)
            //{
            //    if (op10model.Judge == "NG")
            //    {
            //        NG++;
            //        continue;
            //    }
            //    Op20coredata? voltagemodel = OP20List.Where(p => p.SerialNumber == op10model.SerialNumber).FirstOrDefault();
            //    if (voltagemodel == null)
            //    {
            //        NG++;
            //        continue;
            //    }
            //    if (voltagemodel.ResultAc == "NG" || voltagemodel.ResultDc == "NG")
            //    {
            //        NG++;
            //        continue;
            //    }
            //    Op30coredata? thicknessdetectionmodel = OP30List.Where(p => p.SerialNumber == op10model.SerialNumber).FirstOrDefault();
            //    if (thicknessdetectionmodel == null)
            //    {
            //        NG++;
            //        continue;
            //    }
            //    if (thicknessdetectionmodel.FinalJudge == "NG")
            //    {
            //        NG++;
            //        continue;
            //    }
            //    OK++;
            //}
            //model.NG = NG;
            //model.OK = OK;
            return model;

        }
        public async Task<List<ExportQueryModel>> ExportQueryListNew(TotalReq totalReq)
        {
            List<ExportQueryModel> list = new List<ExportQueryModel>();
            List<Op10coredata> OP10List = new List<Op10coredata>();
            List<Op20coredata>? OP20List = new List<Op20coredata>();
            List<Op30coredata> OP30List = new List<Op30coredata>();
            if (!string.IsNullOrEmpty(totalReq.StartTime) && !string.IsNullOrEmpty(totalReq.EndTime))
            {
                DateTime start = DateTime.Parse(totalReq.StartTime);
                DateTime end = DateTime.Parse(totalReq.EndTime);//结束时间加一个小时保证数据完整性
                OP10List = await _dBContext.Op10coreDatas.AsNoTracking().Where(p => p.TestTime >= start && p.TestTime <= end).OrderByDescending(p => p.TestTime).ToListAsync();
                OP20List = await _dBContext.Op20coreDatas.AsNoTracking().Where(p => p.TestTime >= start && p.TestTime <= end.AddHours(1)).ToListAsync();
                OP30List = await _dBContext.Op30coreDatas.AsNoTracking().Where(p => p.TestTime >= start && p.TestTime <= end.AddHours(1)).ToListAsync();
            }
            else if (!string.IsNullOrEmpty(totalReq.StartTime))
            {
                DateTime start = DateTime.Parse(totalReq.StartTime);
                OP10List = await _dBContext.Op10coreDatas.AsNoTracking().Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).ToListAsync();//&&p.PartCode== "P1093818-00-M:SAYH23346624X3Q0"
                OP20List = await _dBContext.Op20coreDatas.AsNoTracking().Where(p => p.TestTime >= start).ToListAsync();
                OP30List = await _dBContext.Op30coreDatas.AsNoTracking().Where(p => p.TestTime >= start).ToListAsync();
            }
            else
            {
                DateTime start = DateTime.Now.AddDays(-2);
                //默认只取3月的数据
                OP10List = await _dBContext.Op10coreDatas.AsNoTracking().Where(p => p.TestTime >= start).OrderByDescending(p => p.TestTime).ToListAsync();
                OP20List = await _dBContext.Op20coreDatas.AsNoTracking().Where(p => p.TestTime >= start).ToListAsync();
                OP30List = await _dBContext.Op30coreDatas.AsNoTracking().Where(p => p.TestTime >= start).ToListAsync();
            }
            if (OP10List.Count > 0)
            {
                int rows = 0;
                foreach (Op10coredata item in OP10List)
                {


                    rows++;
                    ExportQueryModel model = new ExportQueryModel();
                    model.No = rows;
                    model.PartCode = item.SerialNumber;
                    model.Bow = item.HorizontalCamber.ToString();
                    model.BowResult = item.Judge;
                    model.OP10Passageway = item.Passageway;
                    model.Op10CreatTime = item.TestTime.ToString();
                    Op20coredata? op20model = OP20List.Where(p => p.SerialNumber == item.SerialNumber && (item.Judge == "OK" || p.TestTime < item.TestTime.Value.AddMinutes(20)) &&
                   p.TestTime > item.TestTime).OrderByDescending(p => p.TestTime).LastOrDefault();
                    if (op20model != null)
                    {

                        model.Pot = op20model.CurrentDc.Value.ToString("f2");
                        model.voltageDC = op20model.VoltageDc.ToString();
                        model.PotResult = op20model.ResultDc;
                        model.PotAC = op20model.CurrentAc.ToString();
                        model.voltageAC = op20model.VoltageAc.ToString();
                        model.PotResultAC = op20model.ResultAc;
                        model.TotalLength = op20model.TotalLength.ToString();
                        model.OP20Passageway = op20model.Passageway;
                        model.Op20CreatTime = op20model.TestTime.ToString();
                        model.Op20FinalJuge = op20model.finalJudge;
                        Op30coredata? OP30model = OP30List.Where(p => p.SerialNumber == item.SerialNumber && ((op20model.ResultDc == "OK" && op20model.ResultAc == "OK") || p.TestTime < op20model.TestTime.Value.AddMinutes(20)) &&
                     p.TestTime > op20model.TestTime).OrderByDescending(p => p.TestTime).LastOrDefault();
                        if (OP30model != null)
                        {

                            model.Camber = OP30model.FacadeCamber?.ToString();
                            model.ResultCamber = OP30model.CamberJudge?.ToString();
                            model.BackScallop2Pitch = OP30model.BackScallop2Pitch?.ToString();
                            model.BackScallop2Diameter = OP30model.BackScallop2Diameter?.ToString();
                            model.BackScallop3Pitch = OP30model.BackScallop3Pitch?.ToString();
                            model.BackScallop3Diameter = OP30model.BackScallop3Diameter?.ToString();
                            model.FrontScallop2Pitch = OP30model.FrontScallop2Pitch?.ToString();
                            model.FrontScallop2Diameter = OP30model.FrontScallop2Diameter?.ToString();
                            model.FrontScallop3Pitch = OP30model.FrontScallop3Pitch?.ToString();
                            model.FrontScallop3Diameter = OP30model.FrontScallop3Diameter?.ToString();
                            model.FrontThickness7 = OP30model.MaxThickness?.ToString();
                            model.BackThickness7 = OP30model.MiniThickness?.ToString();
                            model.FrontScallop2Pitch = OP30model.FrontScallop2Pitch?.ToString();
                            model.BackScallop2Pitch = OP30model.BackScallop2Pitch?.ToString();
                            model.SC01 = OP30model.sc01?.ToString();
                            model.SC02 = OP30model.sc02?.ToString();
                            model.SC03 = OP30model.sc03?.ToString();
                            model.SC04 = OP30model.sc04?.ToString();
                            model.SED = OP30model.sedJudge?.ToString();
                            model.OP30Passageway = OP30model.Passageway;
                            model.Op30CreatTime = OP30model.TestTime.ToString();
                            model.Op30FinalJuge = OP30model.FinalJudge?.ToString();
                            model.NonPositiveMaxThickness = OP30model.NonPositiveMaxThickness?.ToString();
                            model.NonPositiveMiniThickness = OP30model.NonPositiveMiniThickness?.ToString();
                        }
                    }
                    list.Add(model);
                }
            }
            return list;
        }

        public async Task<List<ExportQueryCount>> ExportQueryListCount(TotalReq totalReq)
        {

            List<ExportQueryCount> list = new List<ExportQueryCount>();
            string start = null;
            string end = null;
            if (!string.IsNullOrEmpty(totalReq.StartTime))
            {
                start = DateTime.Parse(totalReq.StartTime).ToString("yyyy-MM-dd HH:mm:ss");

            }
            else
            {
                //start = DateTime.Now.ToString("yyyy-MM-dd");
                start = DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd HH:mm:ss");
            }
            if (!string.IsNullOrEmpty(totalReq.EndTime))
            {
                end = DateTime.Parse(totalReq.EndTime).ToString("yyyy-MM-dd HH:mm:ss");

            }
            else
            {
                //start = DateTime.Now.ToString("yyyy-MM-dd");
                end = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            }

            // start = start + " 00:00:00";
            // end =end+ " 00:00:00";
            DateTime dt = DateTime.Parse(start);
            DateTime dte = DateTime.Parse(end);

            //从8点开始 8-9
            ExportQueryCount exportQueryCount = new ExportQueryCount();
            List<Op10coredata> shapesList = await _dBContext.Op10coreDatas.AsNoTracking().Where(p => p.TestTime >= dt && p.TestTime <= dte).OrderByDescending(p => p.TestTime).ToListAsync();
            List<Op20coredata> vllist = await _dBContext.Op20coreDatas.AsNoTracking().Where(p => p.TestTime >= dt && p.TestTime <= dte).OrderByDescending(p => p.TestTime).ToListAsync();
            List<Op30coredata> tklist = await _dBContext.Op30coreDatas.AsNoTracking().Where(p => p.TestTime >= dt && p.TestTime <= dte).OrderByDescending(p => p.TestTime).ToListAsync();
            int s = 0;
            int e = 1;
            int loop = (dte.DayOfYear - dt.DayOfYear) * 24 + dte.Hour - dt.Hour;
            for (int i = 0; i < loop; i++)
            {
                DateTime dateStart = dt.AddHours(s + i);
                DateTime dateEnd = dt.AddHours(e + i);
                exportQueryCount = GetCount(shapesList, vllist, tklist, dateStart, dateEnd);
                exportQueryCount.No = i + 1;
                exportQueryCount.DatatimeName = dateStart.ToString("yyyy-MM-dd HH:mm:ss") + "--" + dateEnd.ToString("HH:mm:ss");
                list.Add(exportQueryCount);
            }
            return list;

        }
        public async Task<List<PerformanceRecord>> ExportRecord(TotalReq totalReq)
        {
            DateTime dateTime = DateTime.Now;
            try
            {
                if (!string.IsNullOrEmpty(totalReq.StartTime))
                {
                    dateTime = DateTime.Parse(totalReq.StartTime);
                }

            }
            catch (Exception ex)
            {
            }
            //string sql = string.Format("SELECT t.* FROM PerformanceRecord t WHERE t.CreatedTime IN ( SELECT MAX(CreatedTime)    FROM PerformanceRecord     WHERE CreatedTime >= DATEADD(DAY, -7,'{0}')      GROUP BY CONVERT(DATE, CreatedTime))", dateTime);
            string sql = string.Format(" SELECT * FROM PerformanceRecord  WHERE CreatedTime >= DATEADD(DAY, -10,'{0}') ", dateTime);
            return _dBContext.Database.SqlQuery<PerformanceRecord>(sql).ToList();
        }
        public async Task<List<Equipmentfailurehistory>> ExportAlarm(TotalReq totalReq)
        {
            DateTime dateTime = DateTime.Now;
            try
            {
                if (!string.IsNullOrEmpty(totalReq.StartTime))
                {
                    dateTime = DateTime.Parse(totalReq.StartTime);
                }

            }
            catch (Exception ex)
            {
            }
            //string sql = string.Format("SELECT t.* FROM Equipmentfailurehistory t WHERE t.CreatedTime IN ( SELECT MAX(CreatedTime)    FROM PerformanceRecord     WHERE CreatedTime >= DATEADD(DAY, -7,'{0}')      GROUP BY CONVERT(DATE, CreatedTime))", dateTime);
            string sql = string.Format(" SELECT * FROM equipmentfailurehistory  WHERE CreatedTime >= DATEADD(DAY, -3,'{0}') ", dateTime);
            List<Equipmentfailurehistory> list = _dBContext.Database.SqlQuery<Equipmentfailurehistory>(sql).ToList();

            foreach (var item in list)
            {
                item.ES = TransferDic.GetlanguageText(item.Content, "es");
                item.EN = TransferDic.GetlanguageText(item.Content, "en");
            }
            return list;
        }
        public ExportQueryCount GetCount(List<Op10coredata> shapesList, List<Op20coredata> vllist, List<Op30coredata> tklist, DateTime dateStart, DateTime dateEnd)
        {
            ExportQueryCount model = new ExportQueryCount();
            List<Op10coredata> list1 = shapesList.Where(p => p.TestTime >= dateStart && p.TestTime <= dateEnd).OrderByDescending(p => p.TestTime).ToList();
            if (list1 != null && list1.Count > 0)
            {
                model.BowCount = list1.Count;
                model.BowOK = list1.Where(p => p.Judge == "OK").ToList().Count;
                model.BowNG = list1.Where(p => p.Judge == "NG").ToList().Count;
            }

            List<Op20coredata> list2 = vllist.Where(p => p.TestTime >= dateStart && p.TestTime <= dateEnd).ToList();
            if (list2 != null && list2.Count > 0)
            {
                model.hipotCount = list2.Count;
                model.hipotOK = list2.Where(p => p.finalJudge == "OK").ToList().Count;
                model.hipotNG = list2.Where(p => p.finalJudge == "NG").ToList().Count;
            }

            List<Op30coredata> list3 = tklist.Where(p => p.TestTime >= dateStart && p.TestTime <= dateEnd).ToList();
            if (list3 != null && list3.Count > 0)
            {
                model.CamberCount = list3.Count;
                model.CamberOK = list3.Where(p => p.FinalJudge == "OK").ToList().Count;
                model.CamberNG = list3.Where(p => p.FinalJudge == "NG").ToList().Count;
            }
            return model;
        }

        public Hashtable ExportQuerydetails(TotalReq req)
        {
            List<Shape> splist = new List<Shape>();
            List<Voltagewithstand> vllist = new List<Voltagewithstand>();
            List<Thicknessdetection> tklist = new List<Thicknessdetection>();
            if (!string.IsNullOrEmpty(req.StartTime) && !string.IsNullOrEmpty(req.EndTime))
            {
                DateTime start = DateTime.Parse(req.StartTime);
                DateTime end = DateTime.Parse(req.EndTime);
                splist = _dBContext.Shapes.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).ToList();
                vllist = _dBContext.Voltagewithstands.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).ToList();
                tklist = _dBContext.Thicknessdetections.Where(p => p.CreatedTime >= start && p.CreatedTime <= end).OrderByDescending(p => p.CreatedTime).ToList();
            }
            else if (!string.IsNullOrEmpty(req.StartTime))
            {
                DateTime start = DateTime.Parse(req.StartTime);
                splist = _dBContext.Shapes.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToList();
                vllist = _dBContext.Voltagewithstands.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToList();
                tklist = _dBContext.Thicknessdetections.Where(p => p.CreatedTime >= start).OrderByDescending(p => p.CreatedTime).ToList();
            }
            else
            {
                splist = _dBContext.Shapes.OrderByDescending(p => p.CreatedTime).ToList();
                vllist = _dBContext.Voltagewithstands.OrderByDescending(p => p.CreatedTime).ToList();
                tklist = _dBContext.Thicknessdetections.OrderByDescending(p => p.CreatedTime).ToList();
            }

            List<Detectiondetail> Shapedetaillist = new List<Detectiondetail>();
            foreach (Shape shape in splist)
            {
                Shapedetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == shape.Id).OrderByDescending(p => p.CreatedTime).ToList();
                shape.detaillist = Shapedetaillist;
            }

            List<Detectiondetail> vldetaillist = new List<Detectiondetail>();
            foreach (Voltagewithstand vl in vllist)
            {
                vl.Pushed = true;
                vldetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == vl.Id).OrderByDescending(p => p.CreatedTime).ToList();
                vl.detaillist = vldetaillist;
            }

            List<Detectiondetail> tkdetaillist = new List<Detectiondetail>();
            foreach (Thicknessdetection tk in tklist)
            {
                tk.Pushed = true;
                tkdetaillist = _dBContext.Detectiondetails.Where(p => p.ParentId == tk.Id).OrderByDescending(p => p.CreatedTime).ToList();
                tk.detaillist = tkdetaillist;
            }
            Hashtable hashtable = new Hashtable();
            hashtable.Add("OP10", splist);
            hashtable.Add("OP20", vllist);
            hashtable.Add("OP30", tklist);

            return hashtable;

        }

        public List<Detectiondetail> GetThicknessList(TotalReq totalReq)
        {
            Op30coredata? model = _dBContext.Op30coreDatas.Where(p => p.Id.ToString() == totalReq.ThicknessdetectionID).FirstOrDefault();
            Thicknessdetection? thmodel = _dBContext.Thicknessdetections.Where(p => p.PartCode == model.SerialNumber).OrderByDescending(p => p.CreatedTime).FirstOrDefault();
            List<Detectiondetail> detectiondetails = _dBContext.Detectiondetails.Where(p => p.ParentId == thmodel.Id).ToList();
            List<Detectiondetail> listF = detectiondetails.Where(p => p.DetectedTypeDisplay.Contains("FCT")).ToList();
            List<Detectiondetail> listB = detectiondetails.Where(p => p.DetectedTypeDisplay.Contains("BCT")).ToList();
            listF.AddRange(listB);
            return listF;
        }
        /// <summary>
        /// 历史数据趋势
        /// </summary>
        /// <param name="req"></param>
        public IEnumerable<Op10coredata> HistoryDataTrendsBow(string data, int detectedIndex)
        {
            DateTime startDate = Convert.ToDateTime(data + " 00:00:00");
            DateTime endDate = Convert.ToDateTime(data + " 23:59:59");
            return _dBContext.Op10coreDatas.Where(p => p.TestTime >= startDate && p.TestTime <= endDate).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
        }
        /// <summary>
        /// 历史数据趋势
        /// </summary>
        /// <param name="req"></param>
        public IEnumerable<Op30coredata> HistoryDataTrendsCamOrTl(string data, int detectedIndex)
        {
            DateTime startDate = Convert.ToDateTime(data + " 00:00:00");
            DateTime endDate = Convert.ToDateTime(data + " 23:59:59");
            return _dBContext.Op30coreDatas.Where(p => p.TestTime >= startDate && p.TestTime <= endDate).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
        }
        /// <summary>
        /// 历史数据趋势
        /// </summary>
        /// <param name="req"></param>
        public IEnumerable<Op20coredata> HistoryDataTrendsTl(string data, int detectedIndex)
        {
            DateTime startDate = Convert.ToDateTime(data + " 00:00:00");
            DateTime endDate = Convert.ToDateTime(data + " 23:59:59");
            return _dBContext.Op20coreDatas.Where(p => p.TestTime >= startDate && p.TestTime <= endDate).OrderByDescending(p => p.TestTime).AsNoTracking().ToList();
        }
    }
}
